<template>
    <div class="bg-white shadow-md p-4">
      <Navigation :homeRoute="homeRoute" :currentPage="currentPage" />
    </div>
    <div class="container">
        
        <h1>医疗记录信息</h1>

        <!-- 查询输入框 -->
        <input
            v-model="searchQuery"
            type="text"
            placeholder="按病历ID或患者姓名查询"
            class="search-input"
        />

        <!-- 加载状态 -->
        <div v-if="loading" class="loading">
            <div class="spinner"></div>
            <p>加载中...</p>
        </div>

        <!-- 错误提示 -->
        <div v-if="error" class="error">
            <svg
                class="error-icon"
                fill="currentColor"
                viewBox="0 0 20 20"
                xmlns="http://www.w3.org/2000/svg"
            >
                <path
                    fill-rule="evenodd"
                    d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z"
                    clip-rule="evenodd"
                ></path>
            </svg>
            {{ error }}
        </div>

        <!-- 数据表格 -->
        <div v-if="!loading && !error">
            <table class="table">
                <thead>
                    <tr>
                        <th>病历ID</th>
                        <th>患者ID</th>
                        <th>患者姓名</th>
                        <th>医生ID</th>
                        <th>医生姓名</th>
                        <th>入院时间</th>
                        <th>主诉</th>
                        <th>诊断结果</th>
                        <th>治疗方案</th>
                        <th>更新时间</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-for="item in filteredMedicalRecords" :key="item.record_id">
                        <td>{{ item.record_id }}</td>
                        <td>{{ item.patient_id }}</td>
                        <td>{{ item.patient.real_name }}</td>
                        <td>{{ item.doctor_id }}</td>
                        <td>{{ item.doctor.real_name }}</td>
                        <td>{{ formatDate(item.admission_time) }}</td>
                        <td>{{ item.chief_complaint }}</td>
                        <td>{{ item.diagnosis }}</td>
                        <td>{{ item.treatment_plan }}</td>
                        <td>{{ formatDate(item.update_time) }}</td>
                        <td>
                            <button @click="showEditForm(item)">编辑</button>
                            <button @click="deleteRecord(item.record_id)">删除</button>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>

        <!-- 新增按钮 -->
        <button class="add-button" @click="showAddForm">新增</button>

        <!-- 新增小页面 -->
        <div v-show="isAddFormVisible" class="add-edit-form">
            <h2>新增病历记录</h2>
            <input
                v-model="newRecord.patient_id"
                type="number"
                placeholder="患者ID"
            />
            <input
                v-model="newRecord.doctor_id"
                type="number"
                placeholder="医生ID"
            />
            <input
                v-model="newRecord.admission_time"
                type="datetime-local"
                placeholder="入院时间"
            />
            <input
                v-model="newRecord.chief_complaint"
                type="text"
                placeholder="主诉"
            />
            <input
                v-model="newRecord.diagnosis"
                type="text"
                placeholder="诊断结果"
            />
            <input
                v-model="newRecord.treatment_plan"
                type="text"
                placeholder="治疗方案"
            />
            <button @click="addRecord">保存</button>
            <button @click="closeAddForm">取消</button>
        </div>

        <!-- 编辑小页面 -->
        <div v-show="isEditFormVisible" class="add-edit-form">
            <h2>编辑病历记录</h2>
            <input
                v-model="editedRecord.patient_id"
                type="number"
                placeholder="患者ID"
            />
            <input
                v-model="editedRecord.doctor_id"
                type="number"
                placeholder="医生ID"
            />
            <input
                v-model="editedRecord.admission_time"
                type="datetime-local"
                placeholder="入院时间"
            />
            <input
                v-model="editedRecord.chief_complaint"
                type="text"
                placeholder="主诉"
            />
            <input
                v-model="editedRecord.diagnosis"
                type="text"
                placeholder="诊断结果"
            />
            <input
                v-model="editedRecord.treatment_plan"
                type="text"
                placeholder="治疗方案"
            />
            <button @click="updateRecord">保存</button>
            <button @click="closeEditForm">取消</button>
        </div>
    </div>
</template>

<script setup>
import Navigation from '@/components/Navigation.vue';
import { ref, onMounted, computed } from "vue";
import axios from "axios";

const homeRoute = '/';
const currentPage = '病例管理';
const medicalRecords = ref([]);
const loading = ref(true);
const error = ref(null);
const searchQuery = ref("");
const url = "/medicalitemrecord/findAll";

const isAddFormVisible = ref(false);
const isEditFormVisible = ref(false);
const newRecord = ref({
    patient_id: null,
    doctor_id: null,
    admission_time: null,
    chief_complaint: "",
    diagnosis: "",
    treatment_plan: "",
});
const editedRecord = ref({
    record_id: null,
    patient_id: null,
    doctor_id: null,
    admission_time: null,
    chief_complaint: "",
    diagnosis: "",
    treatment_plan: "",
});

const fetchData = async () => {
    try {
        loading.value = true;
        const response = await axios.get(url);
        medicalRecords.value = response.data;
        console.log("数据加载成功:", medicalRecords.value);
    } catch (err) {
        console.error("数据加载失败:", err);
        error.value = `加载数据失败: ${err.message}`;
    } finally {
        loading.value = false;
    }
};

const filteredMedicalRecords = computed(() => {
    if (!searchQuery.value) {
        return medicalRecords.value;
    }
    const query = searchQuery.value.toLowerCase();
    return medicalRecords.value.filter(
        (item) =>
            String(item.record_id).includes(query) ||
            item.patient.real_name.toLowerCase().includes(query)
    );
});

const formatDate = (timestamp) => {
    const date = new Date(timestamp);
    return date.toLocaleString();
};

const addRecord = async () => {
    try {
        loading.value = true;
        await axios.post("/medicalitemrecord/add", newRecord.value);
        fetchData();
        closeAddForm();
        console.log("新增成功");
    } catch (err) {
        console.error("新增失败:", err);
        error.value = `新增数据失败: ${err.message}`;
    } finally {
        loading.value = false;
    }
};

const showAddForm = () => {
    isAddFormVisible.value = true;
    newRecord.value = {
        patient_id: null,
        doctor_id: null,
        admission_time: null,
        chief_complaint: "",
        diagnosis: "",
        treatment_plan: "",
    };
};

const closeAddForm = () => {
    isAddFormVisible.value = false;
};

const showEditForm = (item) => {
    isEditFormVisible.value = true;
    editedRecord.value = {
       ...item,
        admission_time: new Date(item.admission_time).toISOString().slice(0, 16),
    };
};

const closeEditForm = () => {
    isEditFormVisible.value = false;
};

const updateRecord = async () => {
    try {
        loading.value = true;
        // 使用 POST 方法发送更新请求
        await axios.post('/medicalitemrecord/update', editedRecord.value);
        fetchData();
        closeEditForm();
        console.log("编辑成功");
    } catch (err) {
        console.error("编辑失败:", err);
        error.value = `编辑数据失败: ${err.message}`;
    } finally {
        loading.value = false;
    }
};

const deleteRecord = async (id) => {
    console.log('传递的 recordId 值:', id);
    console.log('传递的 recordId 类型:', typeof id);
    try {
        loading.value = true;
        await axios.post('/medicalitemrecord/delete', { recordId: id });
        fetchData();
        console.log("删除成功");
    } catch (err) {
        console.error("删除失败:", err);
        error.value = `删除数据失败: ${err.message}`;
    } finally {
        loading.value = false;
    }
};

onMounted(() => {
    fetchData();
});
</script>

<style scoped>
.container {
    width: 90%;
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
    font-family: Arial, sans-serif;
}

h1 {
    text-align: center;
    color: #007bff;
    font-size: 28px;
    margin-bottom: 20px;
}

.search-input {
    width: 100%;
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 4px;
    margin-bottom: 20px;
    font-size: 16px;
    outline: none;
    transition: border-color 0.3s ease;
}

.search-input:focus {
    border-color: #007bff;
}

.loading {
    text-align: center;
    padding: 20px;
}

.spinner {
    border: 4px solid rgba(0, 0, 0, 0.1);
    border-left-color: #007bff;
    border-radius: 50%;
    width: 30px;
    height: 30px;
    animation: spin 1s linear infinite;
    margin: 0 auto 10px;
}

@keyframes spin {
    to {
        transform: rotate(360deg);
    }
}

.error {
    background-color: #f8d7da;
    color: #721c24;
    border: 1px solid #f5c6cb;
    border-radius: 4px;
    padding: 10px;
    display: flex;
    align-items: center;
    margin-bottom: 20px;
}

.error-icon {
    width: 20px;
    height: 20px;
    margin-right: 10px;
    color: #721c24;
}

.table {
    width: 100%;
    border-collapse: collapse;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.table th,
.table td {
    padding: 12px;
    border: 1px solid #ddd;
}

.table th {
    background-color: #007bff;
    color: white;
}

.table tr:hover {
    background-color: #f5f5f5;
}

.add-button {
    display: block;
    margin: 20px auto 0;
    padding: 10px 20px;
    background-color: #007bff;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 16px;
    transition: background-color 0.3s ease;
}

.add-button:hover {
    background-color: #0056b3;
}

.add-edit-form {
    border: 1px solid #ccc;
    border-radius: 4px;
    padding: 20px;
    margin: 20px 0;
    background-color: white;
    box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
}

.add-edit-form h2 {
    margin-bottom: 10px;
    color: #007bff;
}

.add-edit-form input {
    width: 100%;
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 4px;
    margin-bottom: 15px;
    font-size: 16px;
    outline: none;
    transition: border-color 0.3s ease;
}

.add-edit-form input:focus {
    border-color: #007bff;
}

.add-edit-form button {
    padding: 10px 20px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 16px;
    margin-right: 10px;
}

.add-edit-form button:nth-child(1) {
    background-color: #007bff;
    color: white;
}

.add-edit-form button:nth-child(2) {
    background-color: #ccc;
    color: white;
}

.add-edit-form button:hover {
    opacity: 0.9;
}
.bg-white {
    background-color: #fff;
  }
  .shadow-md {
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
  }
  .p-4 {
    padding: 1rem;
  }
</style>